package com.lucher.mes.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.ConfigUtil;
import com.lucher.mes.dao.MenuMapper;
import com.lucher.mes.dao.OperatorMapper;
import com.lucher.mes.dao.OperatorrolerefMapper;
import com.lucher.mes.dao.RoleMapper;
import com.lucher.mes.po.Menu;
import com.lucher.mes.po.Operator;
import com.lucher.mes.po.Operatorroleref;
import com.lucher.mes.po.User;
import com.lucher.mes.service.IOperatorService;

@Controller
@RequestMapping("/")  
public class LoginController extends BaseController{
	@Resource  
    private IOperatorService operatorService; 
	@Autowired
	private OperatorrolerefMapper operatorrolerefDao;
	@Autowired
	private MenuMapper menuDao;
	@Autowired
	private RoleMapper roleDao;
	@Resource  
    private OperatorMapper operatorDao; 

    /**
   	 * 进入用户登录界面
   	 * @throws Exception 
   	 */
    @RequestMapping("/login") 
    public String login(User form){    
        return "login"; 
    }
    
    /**
	 * 验证用户登录账号
	 * @throws Exception 
	 */
	@ResponseBody
	// 此标志就是返回json数据给页面的标志
	@RequestMapping(value = "/goLogin")
	public Map<String, Object> goLogin(Operator form, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 封装返回给页面的json对象
		HashMap<String, Object> responseJson = new HashMap<String, Object>();
		responseJson.put("code", "0");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		Operator operator = operatorService.findOperatorByLoginname(form);
		if (operator != null) {
			if (!"在职".equals(operator.getStatus())) {
				responseJson.put("flag", "loginname_error");
				responseJson.put("error", "无效的操作员");
				return responseJson;
			} else if (!operator.getPassword().equals(password)) {
				responseJson.put("flag", "password_error");
				responseJson.put("error", "登录密码不正确");
				return responseJson;
			}
			// 保存操作员到session中
			session.setAttribute("Operator", operator);

			// 判断是否单点登录（不允许同一个操作员登录同时在俩个客户端在线）
			String single_login = ConfigUtil.getConfigFilePath("single_login", "system.properties");
			if (single_login.equals("1")) {
				SessionListener.isLogined(session, form.getLoginname());
			}
			responseJson.put("flag", "0");
			responseJson.put("error", "登录成功");
			return responseJson;
		} else {
			responseJson.put("flag", "loginname_error");
			responseJson.put("error", "登录账号不正确");
			return responseJson;
		}
	}
	
	/**
   	 * 用户登录界面
   	 * @throws Exception 
   	 */
    @RequestMapping("/logined") 
    public String logined(Operator form, Model model, HttpSession session){    
    	Operator operator = (Operator) session.getAttribute("Operator");
    	//菜单对象
		List<Menu> menulist = new ArrayList<Menu>();
		
		if("admin".equals(operator.getLoginname())){//超级管理员admin能查询到所有的菜单
			 
		}else{
			//
			Operatorroleref  operatorroleref = operatorrolerefDao.findByOperatorid(operator.getId());
			if(operatorroleref != null){
				Integer roleid = operatorroleref.getRoleid();
				List<Menu> list = menuDao.queryFirstMenuByRoleid(roleid);
				List<Integer> ids = new ArrayList<Integer>();
				for (Menu pid : list) {
					ids.add(pid.getPid());
				}
				menulist = menuDao.queryMenuByIds(ids);
				if (menulist != null && menulist.size() > 0) {
					for (Menu firstmenu : menulist) {
						Menu findsecondmenu = new Menu();
						findsecondmenu.setRoleid(roleid);
						findsecondmenu.setPid(firstmenu.getId());
						List<Menu> secondmenulist = menuDao.queryRelatedSecondMenu(findsecondmenu);
						firstmenu.setSecondmenulist(secondmenulist);
					}
				} else {
					// menu.setReturninfo("该用户没有权限!");
					System.out.println("该用户没有权限!");
				}
			}
			
			
		}
		
		model.addAttribute("menulist", menulist);
		model.addAttribute("operator", operator);
    	
        return "main";  
    }
	
    /**
	 * 重新回到登录界面（SESSION断掉）
	 */
	@RequestMapping(value = "/noPermission")
	public String noPermission(HttpSession httpSession, HttpServletRequest request, Model model) throws UnsupportedEncodingException {
		return "noPermission";
	}
	
	/**
	 * 退出系统
	 */
	@RequestMapping(value = "/logout")
	public String logout(HttpSession httpSession, HttpServletRequest request, Model model) throws UnsupportedEncodingException {
		
		//清空操作员
		httpSession.setAttribute("Operator", null);
		
		// 判断是否需要验证码
		String captcha_check = ConfigUtil.getConfigFilePath("captcha_check", "system.properties");
		model.addAttribute("captcha_check", captcha_check);
		return "login";
	}
	
}
